package com.example.chatweb.utils;


import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSourceListener;

import java.io.IOException;
import java.util.Objects;

@Slf4j
public class ErnieBotSourceListener extends EventSourceListener {
    @Override
    public void onOpen(okhttp3.sse.EventSource eventSource, okhttp3.Response response) {
        super.onOpen(eventSource, response);
        log.info("文心一言建立SSE连接");
    }

    @Override
    public void onClosed(okhttp3.sse.EventSource eventSource) {
        super.onClosed(eventSource);
        log.info("文心一言关闭SSE连接");
    }

    @Override
    public void onEvent(okhttp3.sse.EventSource eventSource, String id, String type, String data) {
        super.onEvent(eventSource, id, type, data);
        log.info("文心一言返回数据:{}", data);
    }

    @Override
    public void onFailure(okhttp3.sse.EventSource eventSource, Throwable t, okhttp3.Response response) {
        if (Objects.isNull(response)) {
            log.info("文心一言建立SSE连接失败: {}", t);
            eventSource.cancel();
            return;
        }
        ResponseBody body = response.body();
        if (Objects.nonNull(body)) {
            try {
                log.error("文心一言建立SSE连接异常data：{}，异常：{}", body.string(), t);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            log.error("文心一言建立SSE连接异常data：{}，异常：{}", response, t);
        }
        eventSource.cancel();
    }
}
